package tool

import (
	"fmt"
	"gin-demo/model"

	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/xorm"
)

var DbEngine *Orm

type Orm struct {
	*xorm.Engine
}

func OrmEngine(cfg *Config) (*Orm, error) {

	database := cfg.Database

	conn := database.User + ":" + database.Password + "@tcp(" + database.Host + ":" + database.Port + ")/" + database.DbName + "?charset=" + database.Charset
	// conn := `root:root@tcp(127.0.0.1:3306)/ginsql?charset=utf8mb4`

	engine, err := xorm.NewEngine(database.Driver, conn)

	if err != nil {
		return nil, err
	}

	// 是否在控制台打印 sql 语句
	engine.ShowSQL(database.ShowSql)

	// 把 model 实体映射到数据库中创建表
	err = engine.Sync2(
		new(model.SmsCode),
		new(model.Member),
		new(model.FoodCategory),
		new(model.Shop),
	)
	if err != nil {
		return nil, err
	}

	orm := new(Orm)
	orm.Engine = engine

	DbEngine = orm

	InitShopData()

	return orm, nil
}

// 插入数据
func InitShopData() {
	// fmt.Println("DDDDDDDDDDDDDDDDD")
	shops := []model.Shop{
		{
			Id:        1,
			Name:      "儒家",
			Address:   "东城区",
			Phone:     "14879632",
			Status:    1,
			Longitude: 113.27521,
			Latitude:  23.12092,
		},
		{
			Id:        2,
			Name:      "纵横家",
			Address:   "东城区",
			Phone:     "155716352",
			Status:    0,
			Longitude: 116.36868,
			Latitude:  30.12092,
		},
	}

	// 多条数据，需要事务
	session := DbEngine.NewSession()
	defer session.Close()
	// 事务操作，事务开始，执行操作，有错就回滚，结束事务（及commit提交事务）
	err := session.Begin()
	if err != nil {
		fmt.Println(err.Error())
	}
	for _, shop := range shops {
		_, err = session.Insert(shop)
		if err != nil {
			fmt.Println(err.Error())
			// 调用回滚
			session.Rollback()
			return
		}
	}
	// 提交事务
	err = session.Commit()
	if err != nil {
		fmt.Println(err.Error())
	}
}
